<template>
	<view class="container" @tap="clickEmpty">
		
		<scroll-view class="rong-conversations" v-if="authentication ">
		  
		  <!-- <button type="primary" @click="startRong">开始聊天</button> -->
		  
		  <view class="rong-conversation" @tap="gotoChat(conversation)" v-for="(conversation, index) in conversationList" :key="index">
		      <image class="rong-avatar" mode="aspectFill" :src="conversation.avatar" v-if="conversation.avatar"></image>
			  <view class="rong-avatar-default"  v-if="!conversation.avatar"></view>
		      <view class="flex_one content_wrap">
				  <view class="rong-conversation-title ">{{conversation.name}}</view>
				  <view class="rong-conversation-messagecontent " v-if="conversation.type == 1">
				    {{conversation.msgContent}}
				  </view>
				  <view class="rong-conversation-messagecontent " v-if="conversation.type == 2">
				    <!-- <image :src="conversation.msgContent" mode="aspectFill" class="rong-img"></image> -->
					[图片]
				  </view>
				  <view class="rong-conversation-messagecontent " v-if="conversation.type == 3">
				    [声音]
				  </view>
				  <view class="rong-conversation-messagecontent " v-if="conversation.type == 4">
				    [未知消息类型]
				  </view>
				  
			  </view>
			  
		      <!-- <view class="rong-conversation-senttime ">{{conversation.sentTime}}</view> -->
		      <view v-if="conversation.unreadMessageCount > 0" class="rong-conversation-unreadcount">{{conversation.unreadMessageCount}}</view>
		  </view>
		  
		</scroll-view>
		
		<view v-if="!authentication" class="col_center authen_wrap" @tap="goToAuth">
			<image src="../../../static/img/chat/renzheng_icon.png" mode="aspectFill"></image>
			<span class="text">您还未认证</span>
			<span class="text">暂时无法使用患者相关功能！</span>
			<span class="btn">前往认证</span>
		</view>
		
		<view v-if="conversationList && conversationList.length==0 && authentication" class="col_center chat_empty_wrap">
			<image src="../../../static/img/chat/chat_empty.png" mode="aspectFill"></image>
			<span>暂时没有聊天的患者哦~</span>
		</view>
		
		<view v-if="isShowInvalite" class="col_center invalite_wrap" :style="{'top': (isApp?'0upx':'60upx')}">
			<image src="../../../static/img/chat_title_bg.png" mode="aspectFill" class="bg"></image>
			<view class="row_center invalite_item" @tap.stop="goToInvalite">
				<image src="../../../static/img/invalite_person_icon.png" mode="aspectFill"></image>
				<span>邀请患者</span>
			</view>
			<view class="line"></view>
			<view class="row_center invalite_item" @tap.stop="goToMyList">
				<image src="../../../static/img/invalite_list_icon.png" mode="aspectFill" style="width: 35upx;"></image>
				<span>我的患者</span>
			</view>
		</view>
		
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more.vue';
import { BASE_URL,getHcp,getChatStatus,consumers } from '@/utils/api';
// #ifdef APP-PLUS
		const rongIm = uni.requireNativePlugin('GZF-RongIM');
	// #endif
	
 export default {
	components: {uniLoadMore},
	data() {
		return {
			conversationList: [],
			authentication: false,
			unReadCount: 0,
			isShowInvalite: false,
			id: '',
			isApp: false
		};
	},
	watch:{
		conversationList(val){
			let num = 0;
			this.conversationList.map((item) => {
				if(item.unreadMessageCount && (item.unreadMessageCount)>0){
					num += parseInt(item.unreadMessageCount);
				}
			});
			if(num == 0){
				uni.removeTabBarBadge({
					index: 1
				})
			}else{
				uni.setTabBarBadge({
				  index: 1,
				  text: num>99? '99+' : + num+''
				})
			}
			this.consumers();
		}
	},
	
	onNavigationBarButtonTap(e){
		this.isShowInvalite = !this.isShowInvalite;
	},
	onLoad(e) {
		this.isApp = false
		// #ifdef APP-PLUS
			this.isApp = true
		// #endif
		
	},
	onShow() {
		if(!this.authentication){
			
		}else{
			// #ifdef APP-PLUS
			// this.consumers();
			this.getChatMsg();
			// #endif
		}
		this.getHcp();
	},
	methods: {
		getChatMsg(){
			rongIm.getChatMsg('', result => {
				this.consumers();
			})
		},
		async getHcp(){
			let res = await getHcp();
			if(res.status == 0){
				res.data.token = uni.getStorageSync('auth_token');
				uni.setStorageSync("userInfo", res.data);
				
				// #ifdef APP-PLUS
				if(rongIm){
					rongIm.userInfo(JSON.stringify(res.data), result => {
						
					});
				}
				// #endif
				
				
				let approved = res.data.approved;
				if(approved){
					// 认证过了
					this.authentication = true;
					
					// #ifdef APP-PLUS
						this.consumers();
						var webView = this.$mp.page.$getAppWebview();
						webView.setTitleNViewButtonStyle(0, {  
						    color: '#000000',
							 width: '50px'
						});
					// #endif
				}else{
					this.authentication = false;
					// #ifdef APP-PLUS
						var webView = this.$mp.page.$getAppWebview();
						webView.setTitleNViewButtonStyle(0, {  
						    color: '#FFFFFF',
							width: '0px'
						});
					// #endif
				}
				
			}
		},
		consumers(){
			let that = this;
			rongIm.getMsgList("", result => {
				
				if(result){
					let res = JSON.parse(result);
					if(res){
						if(res.length>0){
							let conversationList = [];
							res.map((item) => {
								if(item.msgContent){
									conversationList.push({
										avatar: item.avatar,
										name: item.name,
										unreadMessageCount: item.unreadMessageCount,
										msgContent: item.msgContent,
										id: item.id,
										type: item.type
									});
								}
							});
							if(conversationList.length > 0){
								that.getChatStatus(conversationList);
							}else{
								that.conversationList = [];
								uni.setNavigationBarTitle({
									title:"聊天"
								});
							}
						}else{
							that.conversationList = [];
							uni.setNavigationBarTitle({
								title:"聊天"
							});
						}
						
					}else{
						that.conversationList = [];
						uni.setNavigationBarTitle({
							title:"聊天"
						});
					}
					
				}else{
					that.conversationList = [];
					uni.setNavigationBarTitle({
						title:"聊天"
					});
				}
			})
		},
		async getChatStatus(conversationList){
			let ids = [];
			conversationList.map((item) => {
				ids.push(item.id);
			});
			let params = {
				consumers: ids
			};
			let res = await getChatStatus(params);
			if(res.status == 0){
				let chatList = [];
				conversationList.map((item) => {
					res.data.bind.map((ite) => {
						if(item.id == ite.id){
							item.expiryDate = ite.msg.expiryDate;
							item.targetId = item.id;
							item.status = ite.msg.status;
							chatList.push(item);
						}
					})
				});
				uni.setNavigationBarTitle({
					title:"聊天("+chatList.length+")"
				});
				
				let list = uni.getStorageSync("conversationList");
				if(list && (list.length>0) && (list.length == chatList.length)){
					chatList.map((itee) => {
						list.map((item) => {
							if(item.id == itee.id){
								itee.name = item.name;
								itee.avatar = item.avatar;
							}
						})
					});
					this.conversationList = chatList;
					this.$forceUpdate();
				}else{
					
					this.getConsumers(chatList);
				}
				
			}
		},
		getChatRoomMsg(){
			rongIm.getChatRoomMsg("", result => {
				let res = JSON.parse(result);
				// res.senderUserId
				this.conversationList.map((item) => {
					if(item.id != res.senderUserId){
						this.consumers();
					}
				})
			})
		},
		async getConsumers(chatList) {
			let that = this;
			let res = await consumers();
			if (res.status == 0) {
				console.log(res);
				res.data.map((item) => {
					chatList.map((ite) => {
						if(ite.id == item.id){
							ite.name = item.name;
							ite.avatar = item.avatar;
						}
					});
				});
				this.conversationList = chatList;
				uni.setStorageSync("conversationList", this.conversationList);
				uni.setNavigationBarTitle({
					title:"聊天("+this.conversationList.length+")"
				});
				this.$forceUpdate();
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message,
					duration: 1000
				});
			}
		},
		async startChat(item){
			let res = await startChat(item.id);
			if(res.status == 0){
				item.expiryDate = res.data.expiryDate+"";
				item.targetId = item.id;
				console.log(item);
				rongIm.startTalk(JSON.stringify(item));
			}
		},
		gotoChat: function (item) {
			console.log(item);
			uni.showLoading({
				title: '加载中...'
			})
			rongIm.startTalk(JSON.stringify(item));
			setTimeout(() => {
				uni.hideLoading();
			}, 1000);
		},
		goToAuth(){
			uni.navigateTo({
				url: '/pages/user/info/base'
			})
		},
		clickEmpty(){
			if(this.isShowInvalite){
				this.isShowInvalite = false;
				this.$forceUpdate();
			}
		},
		goToInvalite(){
			this.isShowInvalite = false;
			// uni.navigateTo({
			// 	url:'/pages/webview/webview?id='+this.id+"&name="+uni.getStorageSync("userInfo").name
			// 		+"&title="+uni.getStorageSync("userInfo").title+"&hospital="+uni.getStorageSync("userInfo").hospital
			// 		+"&department="+uni.getStorageSync("userInfo").department
			// })
			
			uni.navigateTo({
				url:'/pages/InvitePatients/InvitePatients?id='+uni.getStorageSync("userInfo").id+"&name="+uni.getStorageSync("userInfo").name
					+"&title="+uni.getStorageSync("userInfo").title+"&hospital="+uni.getStorageSync("userInfo").hospital
					+"&department="+uni.getStorageSync("userInfo").department
			})
		},
		goToMyList(){
			this.isShowInvalite = false;
			uni.navigateTo({
				url:'/pages/patientList/patientList'
			})
		}
		
	}
};
</script>

<style lang="scss">
	.container {width: 100vw;font-size: 28upx;min-height: 100vh;overflow: hidden;color: #6B8082;
		position: relative;background-color: #ffffff;border-top: 2upx solid #e3e3e3;}
	
	.invalite_wrap{
		position: fixed;width: 273upx; height: 237upx;z-index: 1;top: 0upx; right: 26upx;
		.bg{position: absolute; top: 0upx; left: 0upx; width: 100%; height: 100%; z-index: 0;}
		.line{height: 2upx; background: #FFFFFF; width: 122upx; margin-left: 80upx;position: relative;z-index: 1; margin-top: 30upx; margin-bottom: 30upx;}
		.invalite_item{font-size: 30upx; color: #FFFFFF; position: relative; z-index:1;
			image{width: 38upx; height: 38upx;margin-right: 34upx;}
		}
	}
			
	.authen_wrap{
		image{width: 459upx; height: 261upx; margin: 192upx auto 86upx;}
		.text{color: #333333; font-size: 30upx; line-height: 1.3;}
		.btn{color: #FFFFFF; font-size: 34upx; margin-top: 50upx; width: 417upx; height: 88upx; line-height: 88upx; text-align: center;background: #9892ef;}
	}	
	
	.chat_empty_wrap{
		image{width: 459upx; height: 356upx; margin: 269upx auto 69upx;}
		span{color: #BBD5EF; font-size: 34upx;}
	}
	
	.rong-conversations{color: #8E969F; font-size: 13px;}
	.content_wrap{display: flex;flex-direction: column;}
	.rong-authorization-tip{
	  position:absolute;
	  top:30%;
	  left:20%;
	  width:80%;
	  color: #108EE9;
	}
	.rong-authorization-btn{
	  background-color:#108EE9;
	  color:#FFF;
	  position:absolute;
	  top:40%;
	  left:12%;
	  width:80%;
	}
	
	.rong-avatar{
	  height:88rpx;
	  width:88rpx;
	  border-radius: 50%;
	  margin-right: 40upx;
	}
	
	.rong-avatar-default{
		height:88rpx;
		width:88rpx;
		border-radius: 50%;
		margin-right: 40upx;
		background: #C2A2ED;
	}
	
	.rong-img{
	  height:40rpx;
	  width:40rpx;
	}
	
	.rong-conversation{
	  height: 170rpx;
	  box-sizing: border-box;
	  position: relative;
	  padding: 0rpx 10rpx 0rpx 31rpx;
	  border-bottom: 1px solid #F4F4F4;
	  display: flex;
	  flex-direction: row;
	  align-items: center;
	}
	
	.rong-conversation-messagecontent{
	  text-overflow: ellipsis;
	  white-space: nowrap;
	  overflow:hidden;
	  width: 70%;
	}
	.rong-conversation-title{
	  color: #333;
	  font-size: 14px;
	}
	
	.rong-conversation-unreadcount{
	  position: absolute;
	  top: 30rpx;
	  left: 100rpx;
	  background-color: red;
	  border-radius: 50%;
	  color: #FFF;
	  height:30rpx;
	  min-width: 30rpx;
	  text-align:center;
	  line-height: 30upx;
	  box-sizing: border-box;
	  font-size: 18upx;
	}
	
	.rong-conversation-senttime{
	  position: absolute;
	  top: 20rpx;
	  right: 20rpx;
	}
	
</style>
